package com.carsite.webapp.action;

import java.io.OutputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.carsite.Constants;
import com.carsite.model.CheckTable;
import com.carsite.model.Item;
import com.carsite.model.Material;
import com.carsite.model.Product;
import com.carsite.service.CheckTableManager;
import com.carsite.service.DepartmentManager;
import com.carsite.service.ItemManager;
import com.carsite.service.MaterialManager;
import com.carsite.service.ProductManager;
import com.carsite.webapp.form.CheckTableForm;
import com.carsite.webapp.help.Excel_CheckTableInfo;

/**
 * Action class to handle CRUD on a CheckTable object
 * 
 * @struts.action name="checkTableForm" path="/checkTables" scope="request"
 *                validate="false" parameter="method" input="mainMenu"
 * @struts.action name="checkTableForm" path="/editCheckTable" scope="request"
 *                validate="false" parameter="method" input="list"
 * @struts.action name="checkTableForm" path="/saveCheckTable" scope="request"
 *                validate="true" parameter="method" input="edit"
 * @struts.action-set-property property="cancellable" value="true"
 * @struts.action-forward name="edit" path="/WEB-INF/pages/checkTableForm.jsp"
 * @struts.action-forward name="list" path="/WEB-INF/pages/checkTableList.jsp"
 * @struts.action-forward name="search" path="/checkTables.html" redirect="true"
 * @struts.action-forward name="checkTableItems"
 *                        path="/WEB-INF/pages/editCheckTableItems.jsp"
 * @struts.action-forward name="mes" path="/WEB-INF/pages/mes.jsp"    
 * @struts.action-forward name="checkTableInfo" path="/WEB-INF/pages/checkTableInfo.jsp"          
 * 
 */
public final class CheckTableAction extends BaseAction {
	public ActionForward cancel(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward("search");
	}

	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'delete' method");
		}

		ActionMessages messages = new ActionMessages();
		CheckTableForm checkTableForm = (CheckTableForm) form;

		// Exceptions are caught by ActionExceptionHandler
		CheckTableManager mgr = (CheckTableManager) getBean("checkTableManager");
		mgr.removeCheckTable(checkTableForm.getCtId());

		messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
				"checkTable.deleted"));

		// save messages in session, so they'll survive the redirect
		saveMessages(request.getSession(), messages);

		return mapping.findForward("search");
	}

	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'edit' method");
		}

		CheckTableForm checkTableForm = (CheckTableForm) form;

		// if an id is passed in, look up the user - otherwise
		// don't do anything - user is doing an add
		if (checkTableForm.getCtId() != null) {
			CheckTableManager mgr = (CheckTableManager) getBean("checkTableManager");
			CheckTable checkTable = mgr.getCheckTable(checkTableForm.getCtId());
			checkTableForm = (CheckTableForm) convert(checkTable);
			updateFormBean(mapping, request, checkTableForm);
		}
		DepartmentManager deptMgr = (DepartmentManager) getBean("departmentManager");
		List wareList = deptMgr.getWarehouse();
		request.setAttribute("wareList", wareList);
		return mapping.findForward("edit");
	}

	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'save' method");
		}

		// Extract attributes and parameters we will need
		ActionMessages messages = new ActionMessages();
		CheckTableForm checkTableForm = (CheckTableForm) form;
		boolean isNew = ("".equals(checkTableForm.getCtId()) || checkTableForm
				.getCtId() == null);

		CheckTableManager mgr = (CheckTableManager) getBean("checkTableManager");
		CheckTable checkTable = (CheckTable) convert(checkTableForm);
		checkTable.setDTime(new Date());
		mgr.saveCheckTable(checkTable);

		// add success messages
		if (isNew) {
			messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
					"checkTable.added"));
			/*
			 * DepartmentManager deptMgr = (DepartmentManager)
			 * getBean("departmentManager"); List deptList =
			 * deptMgr.getWarehouse(); Department dept=null; for (int i = 0; i <
			 * deptList.size(); i++) { Department d=(Department)
			 * deptList.get(i); String deptName = d.getDeptName(); if
			 * (checkTable.getDeptName().equals(deptName)) { dept=d; } }
			 */
			ProductManager deptMgr = (ProductManager) getBean("productManager");
			MaterialManager materMgr = (MaterialManager) getBean("materialManager");
			List productList = deptMgr.getProductsByDetpName(checkTable
					.getDeptName());
			List materialList = materMgr.getMaterialsByDetpName(checkTable
					.getDeptName());

			request.setAttribute("checkTableId", checkTable.getCtId());
			request.setAttribute("productList", productList);
			request.setAttribute("materialList", materialList);

			// deptMgr.get

			// save messages in session to survive a redirect
			saveMessages(request.getSession(), messages);

			return mapping.findForward("checkTableItems");
			// return mapping.findForward("search");
		} else {
			messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
					"checkTable.updated"));
			saveMessages(request, messages);

			return mapping.findForward("edit");
		}
	}

	public ActionForward search(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'search' method");
		}

		CheckTableForm checkTableForm = (CheckTableForm) form;
		CheckTable checkTable = (CheckTable) convert(checkTableForm);

		CheckTableManager mgr = (CheckTableManager) getBean("checkTableManager");
		request.setAttribute(Constants.CHECKTABLE_LIST, mgr
				.getCheckTables(checkTable));

		return mapping.findForward("list");
	}

	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return search(mapping, form, request, response);
	}

	public ActionForward saveItems(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		System.out.println("saveItems");
		// String[] materialIds=request.getParameterValues("materialId");
		// String[] productIds=request.getParameterValues("productId");
		CheckTableManager mgr = (CheckTableManager) getBean("checkTableManager");
		ItemManager itemMgr = (ItemManager) getBean("itemManager");

		MaterialManager materialManager = (MaterialManager) getBean("materialManager");
		ProductManager productManager = (ProductManager) getBean("productManager");

		Map map = request.getParameterMap();
		Iterator it=map.keySet().iterator();
		while(it.hasNext()){
			String s=(String)it.next();
			System.out.println(s+"->:"+map.get(s));
		}
		String[] materialIds = (String[]) map.get("materialId");
		String[] productIds = (String[]) request
				.getParameterValues("productId");
		String checkTableId = ((String[]) map.get("checkTableId"))[0];
		CheckTable checkTable = mgr.getCheckTable(checkTableId);//getOrder(orderId);
		for (int i = 0; null != materialIds && i < materialIds.length; i++) {
			String materialId = materialIds[i];
			Material material = materialManager.getMaterial(materialId);
			String[] strs=(String[]) map.get(materialId+ "_material_num");
			String materialNum = strs[0];
			Item item = new Item();
			item.setNum(new Integer(materialNum));
			item.setSn(material.getSn());
			item.setTitle(material.getTitle());
			item.setType(material.getTypes());
			
			item.setCheckTable(checkTable);
			//item.setOrder(order);
			checkTable.addItem(item);
			//order.addItem(item);
			 
			//mgr.saveCheckTable(checkTable);//(checkTable);

			itemMgr.saveItem(item);

			System.out.println(materialNum);
		}
		for (int i = 0; null != productIds && i < productIds.length; i++) {
			String productId = productIds[i];
			Product product = productManager.getProduct(productId);
			String productNum = ((String[]) map.get(productId + "_product_num"))[0];
			Item item = new Item();
			item.setNum(new Integer(productNum));
			item.setSn(product.getSn());
			item.setTitle(product.getTitle());
			item.setType(product.getTypes());
			
			checkTable.addItem(item);
			//order.addItem(item);
			item.setCheckTable(checkTable);
			//item.setOrder(order);

			itemMgr.saveItem(item);

			System.out.println(productNum);
		}
		// mgr.saveOrder(order);
		request.setAttribute("mes", "单据已成功增加！");
		return mapping.findForward("mes");

	}
	public ActionForward getCheckTableInfo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String ctId=request.getParameter("ctId");
		CheckTableManager ctManager=(CheckTableManager)this.getBean("checkTableManager");
		CheckTable checkTable=ctManager.getCheckTable(ctId);
		request.setAttribute("checkTable", checkTable);
		return mapping.findForward("checkTableInfo");
	}
	public void getCheckTableInfoExcel(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String ctId=request.getParameter("ctId");
		CheckTableManager ctManager=(CheckTableManager)this.getBean("checkTableManager");
		CheckTable checkTable=ctManager.getCheckTable(ctId);
	//	OutputStream os=response.getOutputStream();
		Excel_CheckTableInfo.createExcelFromBean(checkTable,os);
	 
		////
		/*response.setHeader("Content-Type","application/vnd.ms-excel; charset=utf-8");
		OutputStream os=response.getOutputStream();
		
		ExcelUtil.createExcelFromBeanList(downLoadFile, hkReceiptList,
				methods, cellTitle,os);*/
		////
		// return null;
		//return mapping.findForward("checkTableInfo");
	}
	
}
